<template>
  <el-dialog :title=title
             v-if="open"
             :visible.sync="open"
             :modal= true
             width="80%"
             center
  >
  <div class="app-container">
    <div style="font-size: 20px;">计划信息</div>
    <!--横线组件纯纯为了页面好看-->
    <el-divider></el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="9">
          <el-form-item label="计划编号" prop="planNumber">
            <el-input v-model="form.planNumber" placeholder="请输入计划编号" :readonly="!(optType==='add')"/>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item  label-width="80">
            <el-switch v-model="autoGenFlag"
                       active-color="#13ce66"
                       active-text="自动生成"
                       @change="handleAutoGenChange(autoGenFlag)" v-if="optType === 'add'">
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input v-model="form.planName"  placeholder="请输入计划名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开始日期" prop="planDate">
            <el-date-picker clearable
                            v-model="form.planDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择计划开始日期" style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止日期" prop="materialDeadline">
            <el-date-picker clearable
                            v-model="form.materialDeadline"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择计划截止日期" style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人" prop="applyPersonName">
            <el-input v-model="form.applyPersonName" placeholder="请选择申请人" readonly>
              <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
            </el-input>
            <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请部门" prop="applyDepartment">
            <el-input v-model="form.applyDepartment" readonly>
            </el-input>

          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--横线组件纯纯为了页面好看-->
    <el-divider></el-divider>
    <el-row style="margin-bottom: 20px;">
      <el-col :span="1.5">
        <div style="font-size: 20px; margin-top: 5px">采购物料</div>
      </el-col>
<!--      <el-col :span="5">
        <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">点击添加物料</el-button>
      </el-col>-->
    </el-row>
    <el-table border ref="addGoodsTable" :data="addGoodsList">
      <el-table-column label="物料编号" align="center" prop="itemCode"/>
      <el-table-column label="物料名称" align="center" prop="itemName"/>
      <el-table-column label="规格型号" align="center" prop="specification"/>
      <el-table-column label="分类" align="center" prop="itemTypeName"/>
      <el-table-column
        v-for="col in columnsConfig"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :align="col.align"
        v-if="col.show">
      </el-table-column>
<!--      <el-table-column label="采购单价" align="center" prop="estimatedUnitPrice">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.estimatedUnitPrice" placeholder="请输入价格"
                    size="mini"
                    style="width:100px"
                    maxlength="10"
                    @keyup.native="scope.row.estimatedUnitPrice = scope.row.estimatedUnitPrice = scope.row.estimatedUnitPrice.replace(/[^\d.]/g,'');
                                   scope.row.estimatedUnitPrice = scope.row.estimatedUnitPrice.replace(/\.{2,}/g,'.');
                                   scope.row.estimatedUnitPrice = scope.row.estimatedUnitPrice.replace(/^\./g,'');
                                   scope.row.estimatedUnitPrice = scope.row.estimatedUnitPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                   scope.row.estimatedUnitPrice = scope.row.estimatedUnitPrice.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
                    @input="handleEdit(scope.$index, scope.row)"></el-input>
        </div>
      </el-table-column>-->
      <el-table-column label="单位" align="center" prop="unitOfMeasure" fixed="right"/>
      <el-table-column label="采购数量" align="center" prop="quantity" fixed="right" width="150">
        <div class="item" slot-scope="scope">
          <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1" :max="90000000000" size="mini" style="width:130px"  />
        </div>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="clientName" width="300" fixed="right">
        <div class="item" slot-scope="scope">
          <el-input v-model="scope.row.clientName" placeholder="请选择客户" readonly>
            <el-button
              slot="append"
              @click="handleSelectClient(scope.row)"
              icon="el-icon-search"
            >
            </el-button>
          </el-input>
        </div>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" fixed="right" width="200">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.remark" placeholder="请输入备注" size="mini" style="width:130px"></el-input>
        </div>
      </el-table-column>
<!--      <el-table-column label="采购总价" align="center" prop="total">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.total" placeholder="采购总价" size="mini" style="width:100px" readonly="readonly"></el-input>
        </div>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="deleteGoodsList(scope.row)"
          >删除商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <ClientSelect ref="clientSelect" @onSelected="onClientSelected" > </ClientSelect>
    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitForm">保存采购计划</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>

  <!--选择商品信息弹出框-->
    <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
  </div>
  </el-dialog>
</template>

<script>
import {addPlan, updatePlan,getPlan} from "@/api/mes/cg/plan";
import {genCode} from "@/api/system/autocode/rule"
import ItemSelect  from "@/views/mes/cg/plan/itemSelect.vue";
import ClientSelect from "@/components/clientSelect/single.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
import {getUserProfile} from "@/api/system/user";
import UserSelect from "@/components/userSelect/single.vue";
/*import VendorSelect from "@/components/vendorSelect/single.vue";*/
export default {
  name: "add",
  components: {UserSelect, ClientSelect, ItemSelect },
  dicts: ['erp_payment_type'],
  data() {
    return {
      autoGenFlag: false,
      optType: undefined,
      open:false,
      title:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 添加的商品信息表格数据
      addGoodsList: [],
      // 供应商列表
      vendorList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planNumber: [
          { required: true, message: "计划编号不能为空", trigger: "blur" }
        ],
        planDate: [
          { required: true, message: "计划日期不能为空", trigger: "change" }
        ],
        materialDeadline: [
          { required: true, message: "物料截止日期不能为空", trigger: "change" }
        ],
       /* vendorName: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        paymentType: [
          { required: true, message: "付款方式不能为空", trigger: "change" }
        ]*/

      },
      row:{},
      columnsConfig:[],
      user: {},
    };
  },
  created() {
    this.getItemBase();
    this.getUser();
   /* this.getList();
    //查询商品表方法
    this.getGoodsList();
    //查询供应商列表方法
    this.getSupplierlist();*/
  },
  methods: {
    init(){
      this.form = {
        planNumber:null,
        planName:null,
        planDate:new Date().toISOString().split('T')[0],
        materialDeadline:null,
        remarks:null,
        estimatedCost:null,
        vendorId:null,
        vendorName:null,
        paymentType:null,
        vendorCode:null,
        contact:null,
        contactTel:null,
        applyPersonId:this.user.userId,
        applyPersonName:this.user.nickName,
        applyDepartment:this.user.dept.deptName,
        applyDepartmentId:this.user.dept.deptId,
      };
      this.resetForm("form");
      this.row = {};
    },
    update(id){
      getPlan(id).then(response => {
        this.form = response.data;
        this.addGoodsList=response.data.cgPurchasePlanDetails;
      });
    },
    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },

    //商品小计
    /*getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "total"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      this.form.estimatedCost=sums[7];
      return sums;
    },*/

    //商品总价计算
    /*handleEdit(index, row) {
      if(row.quantity && row.estimatedUnitPrice){
        row.total = parseFloat(Number(row.quantity)*Number(row.estimatedUnitPrice)).toFixed(2)
      }
    },*/
    // 取消按钮
    cancel() {
      this.open = false;
      this.$parent.getList();
    },
    /** 新增采购商品按钮操作 */
    handleAdd() {
      this.$refs.itemSelect.showFlag=true;
      this.$refs.itemSelect.selectedRows1=this.addGoodsList;
      this.$refs.itemSelect.resetQuery();
    },
    /** 新增提交按钮 */
    submitForm() {
      let that = this;
      that.$modal.confirm('是否确认保存采购计划？').then(function() {
        that.$refs["form"].validate (valid => {
          if (valid) {
            //判断是否添加商品
            if (that.addGoodsList.length === 0) {
              that.$modal.msgError("请添加商品");
              return;
            }
            if (that.addGoodsList.length !== 0) {
              for (let i = 0; i < that.addGoodsList.length; i++) {
                /*if (that.addGoodsList[i].estimatedUnitPrice === null || that.addGoodsList[i].estimatedUnitPrice === "") {
                  that.$modal.msgError("请填写采购单价");
                  return;
                }*/
                if (that.addGoodsList[i].quantity === null || that.addGoodsList[i].quantity === undefined) {
                  that.$modal.msgError("请填写采购数量");
                  return;
                }
                if (that.addGoodsList[i].quantity <= 0) {
                  that.$modal.msgError("请填写正确的采购数量");
                  return;
                }
              }
            }
            that.form.cgPurchasePlanDetails=that.addGoodsList;

            console.log(that.form)
            if(that.form.planId){
              updatePlan(that.form).then(response => {
                that.$modal.msgSuccess("修改成功");
                that.open = false;
                that.$parent.getList();
                that.cancel();
              })
            }else{
              //调取新增接口
              addPlan(that.form).then(response => {
                that.$modal.msgSuccess("新增成功");
                that.open = false;
                that.$parent.getList();
                that.cancel();
              });
            }
          }
        })


      });
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('PURCHASE_PLAN_CODE').then(response =>{
          this.form.planNumber = response;
        });
      }else{
        this.form.planNumber = null;
      }
    },
    //物料选择弹出框
    onItemSelected(obj){
      if (this.addGoodsList && this.addGoodsList.length > 0) {
        this.addGoodsList.forEach((row, index) => {
          obj.find((item1) => {
            if (item1.itemCode == row.itemCode) {
              item1.clientId = row.clientId;
              item1.clientCode = row.clientCode;
              item1.clientName = row.clientName;
              item1.quantity = row.quantity;
              item1.total = row.total;
              item1.remark = row.remark;
            }
          })
        })
      }
      this.addGoodsList = obj;
      /*let one=this.addGoodsList.find(item=>item.itemCode===obj.itemCode);
      if(one){
        this.$modal.msgError("该物料已添加");
        return;
      }
      let data= {
        itemId: obj.itemId,
        itemCode: obj.itemCode,
        itemName: obj.itemName,
        itemType: obj.itemType,
        itemTypeName: obj.itemTypeName,
        specification: obj.specification,
        unitOfMeasure: obj.unitOfMeasure,
        estimatedUnitPrice: obj.referencePrice,
        quantity: 0,
        total: 0
        ,itemBrand: obj.itemBrand,
        itemColor: obj.itemColor,
        itemTechReq: obj.itemTechReq,
        itemModel: obj.itemModel
      }
      this.addGoodsList.push(data);*/
    },
    handleSelectClient(row){
      this.$refs.clientSelect.showFlag = true;
      this.row = row;
    },
    //客户选择弹出框
    onClientSelected(obj){
      let index=this.addGoodsList.findIndex(item=>item.itemId==this.row.itemId);
      if(obj != undefined && obj != null){
        this.row.clientId = obj.clientId;
        this.row.clientCode = obj.clientCode;
        this.row.clientName = obj.clientName;
        this.addGoodsList.splice(index,1,this.row);
      }
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.applyPersonName = obj.nickName;
        this.form.applyPersonId = obj.id;
        this.form.applyDepartment=obj.dept.deptName;
        this.form.applyDepartmentId=obj.dept.deptId;
      }
    },
    /*//供应商选择
    handleSelectVendor(){
      this.$refs.vendorSelect.showFlag = true;
    },*/
    //供应商选择弹出框
    /*onVendorSelected(obj){
      if(obj != undefined && obj != null){
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        if(obj.contact1 !=null && obj.contact1Tel !=null){
        this.form.contact=obj.contact1;
        this.form.contactTel=obj.contact1Tel;
        }else{
          this.form.contact=obj.contact2;
          this.form.contactTel=obj.contact2Tel;
        }
      }
    },*/
  }
};
</script>

<style scoped>

</style>
